package com.atguigu.springcloud.controller;


import java.util.Date;
import java.util.Map;
import java.util.Set;

import javax.annotation.Resource;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.atguigu.springcloud.entity.CommonResult;
import com.atguigu.springcloud.entity.Payment;
import com.atguigu.springcloud.service.PaymentService;

import cn.hutool.core.date.DateUtil;
import cn.hutool.json.JSONObject;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;

@RestController
@Slf4j
@Api("PaymentController")
@RequestMapping(value = "/payment")
public class PaymentController {
	@Resource
	private PaymentService paymentService;

	@Value("${server.port}")
	private String serverPort;
	@Resource
	private DiscoveryClient discoveryClient;
	
	@ApiOperation("新增")
	@PostMapping(value = "/create")
	public CommonResult create(@RequestBody Payment payment) {
		boolean result = paymentService.save(payment);
		log.info("插入结果：" + result);
		if (result) {
			return CommonResult.ok( "插入数据库成功,端口号：" + serverPort, payment);
		} else {
			return CommonResult.error("插入数据库失败");
		}
	}
	@ApiOperation("查询")
	@GetMapping(value = "/get/{id}")
	public CommonResult getPaymentById(@PathVariable("id") Long id) {
		Payment payment = paymentService.getById(id);
		log.info("查询结果：" + payment);
		if (payment != null) {
			return CommonResult.ok( "查询成功,端口号：" + serverPort, payment);          

		} else {
			return CommonResult.error("没有对应记录，查询ID:" + id);
		}
	}
	/**
	 * 获取微服务的信息
	 * @return
	 */
	@ApiOperation("获取微服务的信息")
	@GetMapping(value = "/discovery")
	public CommonResult getDiscovery() {
		discoveryClient.getServices().forEach(service ->{
			log.info(service);
		});
		discoveryClient.getInstances("CLOUD-PAYMENT-SERVICE").forEach(instances->{
			log.info(instances.getInstanceId()+"\t"+instances.getPort()+"\t"+instances.getUri());
		});
		return	CommonResult.ok(discoveryClient.getServices());
	}
	@ApiOperation("获取当前微服务的信息")
	@GetMapping(value = "/info")
	public CommonResult info() {
		JSONObject json = new JSONObject();
			json.put("description", discoveryClient.description());
			json.put("port", serverPort);
			json.put("date", DateUtil.now());
		return	CommonResult.ok(json);
	}
}
